<?php
include_once __DIR__ . "/../base.php";

class huilian2 extends base
{
    protected $rsaPublicKey = "";
    protected $rsaPrivateKey = "";
    protected $sys_id = "";
    protected $product_id = "";
    public $callback_url = "";
    // protected $jigou = "6666000144295701";


    public function __construct($setting)
    {
        // $this->account = $setting['account'];
        // $this->key = $setting['key'];  //密钥
        $this->rsaPublicKey = $setting['rsaPublicKey'];
        $this->rsaPrivateKey = $setting['rsaPrivateKey'];
        $this->sys_id = $setting['sys_id'];
        $this->product_id = $setting['product_id'];
        $this->callback_url = $setting['callback_url'];
    }
    // 验证签名
    function verifySign_sort($signature, $data, $alg = OPENSSL_ALGO_SHA256)
    {
        $key = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($this->rsaPublicKey, 64, "\n", true) . "\n-----END PUBLIC KEY-----";
        return openssl_verify($data, base64_decode($signature), $key, $alg);
    }
    // 生成签名
    function sha_with_rsa_sign($data,  $alg = OPENSSL_ALGO_SHA256)
    {
        ksort($data);
        $postData = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        $key = "-----BEGIN PRIVATE KEY-----\n" . wordwrap($this->rsaPrivateKey, 64, "\n", true) . "\n-----END PRIVATE KEY-----";
        $signature = '';
        try {
            openssl_sign($postData, $signature, $key, $alg);
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
        return base64_encode($signature);
    }
    // 设置appid关联配置等
    public function config()
    {
        $url = "https://api.huifu.com/v2/merchant/busi/config";
        $data = [
            "req_seq_id" => time(),
            "req_date" => date('Ymd', time()),
            "huifu_id" => $this->sys_id,
            "fee_type" => "01",
            "wx_applet_app_id" => "wxff3e969d7c6364f9",
            "wx_applet_secret" => "541a79a580b9965bebb4bb75ad959ad1",
        ];
        $sign = $this->sha_with_rsa_sign($data);
        $params = [
            "sys_id" => $this->sys_id,
            "product_id" => $this->product_id,
            "data" => $data,
            "sign" => $sign
        ];
        $this->log("huifu2配置请求信息：");
        $this->log(json_encode($params));
        $return_str  =  $this->httpRequest($url, 'POST', json_encode($params), '', '', [
            'Content-Type:application/json'
        ]);
        $this->log("huifu2配置返回信息：");
        $this->log($return_str);

        return json_decode($return_str, true);
    }
    public function submitOrder($data)
    {
        $submitUrl = "https://api.huifu.com/v2/trade/payment/jspay";
        $wx_data = [
            "sub_appid" => $data['SubAppId'],
            "openid" => $data['OpenId'],
            "sub_openid" => $data['OpenId'],
            "body" => $data['OutTradeNo'],
        ];
        $paydata = [
            "req_date" => date('Ymd', time()),
            "req_seq_id" => $data['OutTradeNo'],
            "huifu_id" => $this->sys_id,
            "goods_desc" => $data['Body'],
            "trade_type" => "T_MINIAPP",  //T_MINIAPP小程序，T_JSAPI: 微信公众号
            "trans_amt" => number_format($data['TotalAmount'] / 100, 2),
            "notify_url" => $this->callback_url,
            "wx_data" => json_encode($wx_data),
        ];
        $sign = $this->sha_with_rsa_sign($paydata);

        $params = [
            "sys_id" => $this->sys_id,
            "product_id" => $this->product_id,
            "data" => $paydata,
            "sign" => $sign
        ];
        $this->log("汇联2请求信息：");
        $this->log(json_encode($params));
        $return_str  =  $this->httpRequest($submitUrl, 'POST', json_encode($params), '', '', [
            'Content-Type:application/json'
        ]);
        $this->log("汇联2返回信息：");
        $this->log($return_str);

        $return_data = json_decode($return_str, true);

        // {"data":{"bank_code":"FAIL","bank_message":"sub_mch_id与sub_appid不匹配","hf_seq_id":"002900TOP2B231208224647P847ac139c2b00000","huifu_id":"6666000144295701","party_order_id":"03222312088200798015123","req_date":"20231208","req_seq_id":"1702046807","resp_code":"90000000","resp_desc":"业务执行失败[失败]","trade_type":"T_MINIAPP","trans_amt":"0.01","trans_stat":"F"},"sign":"QDXydDkfCHbM+6wak31fqod3NV1GoYM6WyXU66fvmT62s1SgXTTgtZqMMeq7jjspr1c+hVzHWtJ5d0V9TTdTeRAC6E33UNCDUoD2b1lf3adNw0dl/bcxahmA/k0IygvCdPB8UZmyUHSLdxwT0ayFrqmDtviXiw3iqJBhO4vjrlzPzyBUtVmKntehMzXIgq0fSMPpx7WDILhc08zIGbwmRgEfKSDunF9Ie4G//d+FgEOGgP3nF9ZYegvGaMwpoxJjR/QEGL4+Kpz4cQsmYGV4BJzS98nirBW18vdD6+Q/gVEab6dDkK+pjTGKjywyA4mcye30QD084CDW2VdrSrOFWA=="}
        if ($return_data['data']['resp_code'] == "00000100") {
            $json = json_decode($return_data['data']['pay_info'], true);
            $json['timestamp'] = $json['timeStamp'];
            // $json['pay_order_sn'] = $return_data['upOrderId'];

            return array('status' => 1, 'payInfo' => $json, 'pay_order_sn' => $return_data['data']['hf_seq_id']);
        } else {
            if (isset($return_data['data']['resp_code'])) {
                return ['status' => 0, 'msg' => "下单失败:" . $return_data['data']['resp_desc']];
            }
        }
    }
    public function notifyOrder($params)
    {
        $sign = $params['sign'];
        $resData = [
            'code' => 200,
            "data" => [],
            "msg" => "",
            "resp" => 'fail'
        ];
        $resp_data = json_decode($params['resp_data'], true);

        $isPass = $this->verifySign_sort($sign, $params['resp_data']);
        if (!$isPass) {
            $resData['code'] = 500;
            $resData['msg'] = "签名不匹配:sign" . $sign;
            return $resData;
        }
        if ($resp_data['trans_stat'] == "S") {
            $resData["data"] = [
                "order_sn" =>  $resp_data['req_seq_id'],
                "pay_order_sn" => $resp_data['hf_seq_id']
            ];
            $resData["resp"] = "SUCCESS";
            return $resData;
        } else {
            $resData['code'] = 500;
            $resData['msg'] = "支付失败回调";
            $this->log("汇联2支付失败回调请求参数：");
            $this->log(json_encode($params));
            return $resData;
        }
    }
    public function refund($order_sn, $refund_order_sn, $refund_price, $remark, $pay_order_sn = "", $order)
    {
        // refund_price 单位分
        $url = "https://api.huifu.com/v2/trade/payment/scanpay/refund";
        $params = [
            "req_date" => date('Ymd', time()),
            "req_seq_id" => $refund_order_sn,
            "huifu_id" => $this->sys_id,
            "ord_amt" => number_format($refund_price / 100, 2),
            "org_req_date" => date('Ymd', strtotime($order['created_at'])),
            "org_req_seq_id" => $order_sn,
            "remark" => $remark
        ];
        $data = [
            "sys_id" => $this->sys_id,
            "product_id" => $this->product_id,
            "data" => $params,
            "sys_id" => $this->sys_id,
            "sign" => $this->sha_with_rsa_sign($params),
        ];
        $this->log("hufiu2退款请求信息：");
        $this->log(json_encode($data));

        $return_str = $this->httpRequest($url, "POST", json_encode($data), '', '', [
            'Content-Type:application/json'
        ]);
        $this->log($order_sn . "huifu2退款响应信息：");
        $this->log($return_str);
        $return_data = json_decode($return_str, 1);

        $data = [
            "code" => 500,
            "data" => [],
            "msg" =>  ''
        ];

        if ($return_data['data']['resp_code'] == "00000100" && ($return_data['data']['trans_stat'] == "P" || $return_data['data']['trans_stat'] == "S")) {
            $data['code'] = 200;
            $data['msg'] = $return_data['data']['resp_desc'];
            return $data;
        } else {
            if (isset($return_data['data']['resp_code'])) {
                $data['code'] = 500;
                $data['msg'] = "退款失败，原因：" . $return_data['data']['resp_desc'];
                return $data;
            }
        }
    }
}
